<template>
	<view class="padding">
		<tui-org-tree :treeData="treeData" @click="handleClick"></tui-org-tree>
	</view>
</template>

<script>
	export default {
		onLoad: function(option) {
			if (option.userId && option.userName) {
				this.info.userIds.push(option.userId);
				this.userName = option.userName;
				this.getOrgTree();
			} else {
				this.$utils.modal("提示", "没有选择用户，无法更换组织", false, flag => {
					if (flag) {
						uni.navigateBack();
					}
				});
			}
		},
		onShow: function() {},
		onHide: function() {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.emit('refresh', {});
		},
		onReady: function() {},
		onReachBottom: function() {},
		onNavigationBarButtonTap: function(option){
			if (option.type == "home") {
				uni.navigateBack({
					delta: getCurrentPages().length - 1
				});
			}
		},
		data() {
			return {
				userName: null, // 用户名称
				info: {
					userIds: [],
					orgId: null
				},
				treeData: []
			};
		},
		methods: {
			// 获取组织树
			getOrgTree() {
				this.$http.post("/admin/sys/rbac/org/getOrgTree", {}, res => {
					let treeData = [{
							id: "single",
							label: "独立用户"
						}]
						.concat(res.data);
					this.handleOrgTree(treeData);
					this.treeData = treeData;
				}, false, false, true);
			},
			// 处理树
			handleOrgTree(treelist) {
				for(let item of treelist) {
					item.value = item.id;
					item.text = item.label;
					if (item.children && item.children.length > 0) {
						this.handleOrgTree(item.children);
					} else {
						item.children = [];
					}
				}
			},
			// 点击组织树
			handleClick(node) {
				this.$utils.modal("提示", `是否将用户${this.userName}更换到${node.label}组织下?`, true, flag => {
					if (flag) {
						this.info.orgId = node.id == "single" ? null : node.id;
						this.$http.post("/admin/sys/rbac/user/changeOrgId", this.info, res => {},true, true, true);
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
</style>
